import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, InputNumber, Select, message } from 'antd';
import { categoryService } from '../services/categoryService';

const { TextArea } = Input;
const { Option } = Select;

const FurnitureForm = ({ visible, onCancel, onSubmit, furniture, title }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [categories, setCategories] = useState([]);

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const response = await categoryService.getAllCategories();
      setCategories(response.data);
    } catch (error) {
      console.error('获取分类列表失败:', error);
    }
  };

  useEffect(() => {
    if (visible) {
      fetchCategories();
    }
  }, [visible]);

  useEffect(() => {
    if (visible && furniture) {
      form.setFieldsValue(furniture);
    } else if (visible) {
      form.resetFields();
    }
  }, [visible, furniture, form]);

  const handleSubmit = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      await onSubmit(values);
      form.resetFields();
    } catch (error) {
      console.error('表单验证失败:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      destroyOnClose
      width={600}
    >
      <Form
        form={form}
        layout="vertical"
        name="furnitureForm"
      >
        <Form.Item
          name="name"
          label="家具名称"
          rules={[
            { required: true, message: '请输入家具名称' },
            { min: 2, message: '家具名称至少2个字符' },
            { max: 100, message: '家具名称最多100个字符' }
          ]}
        >
          <Input placeholder="请输入家具名称" />
        </Form.Item>

        <Form.Item
          name="description"
          label="描述"
          rules={[
            { max: 500, message: '描述最多500个字符' }
          ]}
        >
          <TextArea 
            placeholder="请输入家具描述" 
            rows={3}
            showCount
            maxLength={500}
          />
        </Form.Item>

        <Form.Item
          name="price"
          label="价格"
          rules={[
            { required: true, message: '请输入价格' },
            { type: 'number', min: 0, message: '价格必须大于等于0' }
          ]}
        >
          <InputNumber
            placeholder="请输入价格"
            style={{ width: '100%' }}
            min={0}
            precision={2}
            formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            parser={value => value.replace(/¥\s?|(,*)/g, '')}
          />
        </Form.Item>

        <Form.Item
          name="stock"
          label="库存"
          rules={[
            { required: true, message: '请输入库存数量' },
            { type: 'number', min: 0, message: '库存必须大于等于0' }
          ]}
        >
          <InputNumber
            placeholder="请输入库存数量"
            style={{ width: '100%' }}
            min={0}
          />
        </Form.Item>

        <Form.Item
          name="categoryId"
          label="分类"
          rules={[
            { required: true, message: '请选择分类' }
          ]}
        >
          <Select placeholder="请选择分类">
            {categories.map(category => (
              <Option key={category.id} value={category.id}>
                {category.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default FurnitureForm;
